package ru.pb.auth.network.engine.game;

import org.apache.log4j.Logger;

import ru.pb.auth.network.clients.GameServerClient;
import ru.pb.auth.network.engine.auth.AuthClientPacketListenerHandler;
import ru.pb.auth.network.engine.game.packets.FromGameServerClientToAuthServerPacket;
import ru.pb.auth.network.engine.game.packets.receivable.AUTH_REQUEST;
import ru.pb.global.network.engine.buffer.NioBuffer;
import ru.pb.global.network.engine.core.emuns.ConnectionState;
import ru.pb.global.network.engine.core.interfaces.IPacketHandler;
import ru.pb.global.network.utils.NetworkUtil;

/**
 * @author: Felixx
 *          Слушает пакеты гейм серверов.
 */
public class GameServerPacketListenerHandler implements IPacketHandler<GameServerClient>
{
	private static Logger _log = Logger.getLogger(AuthClientPacketListenerHandler.class);
	private boolean _aviableConnections = true;

	@Override
	public FromGameServerClientToAuthServerPacket handle(NioBuffer buf, GameServerClient client)
	{
		boolean SHOW_ALL_PACKET = false;
		if(SHOW_ALL_PACKET)
		{
			NioBuffer temp = buf.duplicate();
			int allSize = temp.limit();
			int dataSize = allSize -= 4;
			int opcode = temp.getUnsignedShort();
			_log.info("Packet id: " + opcode + "; size: " + dataSize);
		}

		FromGameServerClientToAuthServerPacket packet = null;
		ConnectionState state = client.getState();
		int opcode = buf.getUnsignedShort();

		if(_aviableConnections)
		{
			// _log.info("OPCODE: " + opcode);
			// _log.info("position: " + buf.position());
			switch(state)
			{
				case CONNECTED:
				{
					switch(opcode)
					{
						case 0x00:
						{
							break;
						}
						case 0x01:
						{
							packet = new AUTH_REQUEST();
							break;
						}
						default:
						{
							debugOpcode(opcode, state, client, buf);
						}
					}
					break;
				}
			}
			return packet;
		}
		else
		{
			_log.info("НЕУДАЧНМК!");
		}
		return null;
	}

	private void debugOpcode(int opcode, ConnectionState state, GameServerClient client, NioBuffer buf)
	{
		_log.info("Unknown Opcode: " + opcode + " for state: " + state.name() + " from IP: " + client.getIPString());
		_log.info(NetworkUtil.printData(buf));
	}
}